/*
 * Copyright 2010-2011 CGT&DC ISA RAS
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package websolve.workflow.wfms.security;

import java.io.File;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.core.SecurityContext;

import org.codehaus.jettison.json.JSONObject;

import websolve.everest.security.AccessPolicy;
import websolve.everest.security.Authenticator;

public class AuthAPIServlet extends javax.servlet.http.HttpServlet {
    
    private Authenticator auth;
    private AccessPolicy globalAccessPolicy;

    @Override
    public void init() throws ServletException {
        try {
            auth = new Authenticator();
            globalAccessPolicy = 
                    new AccessPolicy(new File("conf/allow"), new File("conf/deny"));
        } catch (IOException e) {
            e.printStackTrace();
            throw new ServletException(e);
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            SecurityContext sc = auth.authenticate(req);

            JSONObject authInfo = new JSONObject();
            if (sc == null || !sc.isSecure()) {
                authInfo.put("secure", false);
            } else {
                authInfo.put("secure", true);
                if (sc.getUserPrincipal() != null) {
                    String user = sc.getUserPrincipal().getName();
                    authInfo.put("user", user);
                    
                    // guest mode detection
                    if (globalAccessPolicy.isAllowed(user) && !globalAccessPolicy.isDenied(user)) {
                        authInfo.put("guest", false);
                    } else {
                        authInfo.put("guest", true);
                    }
                }
            }

            resp.setContentType("text/html");
            resp.getWriter().write(authInfo.toString());
        } catch (Exception e) {
            throw new ServletException(e);
        }
    }

    private static final long serialVersionUID = 4930360384923362087L;
}
